import URL from '../config/URL'
import crypt from '../common/crypt'

const {
  server
} = URL
const noop = () => {}
const request = ({ url = server, success = noop, data, fail = noop, method = 'POST'}) => {
  const failCb = (title) => {
    fail()
    wx.showModal({
      showCancel: false,
      content: title || '网络异常，请检查网络连接'
    })
  }
  const queryParams = {
    openid: global.openid,
    ...data
  }
  wx.request({
    method,
    data: {
      q: crypt.encrypt(queryParams)
    },
    url,
    success: (response) => {
      let res = response.data
      try {
        res = crypt.decrypt(res)
      } catch (e) {
        res = {
          errno: -1,
          errmsg: '服务繁忙，请稍后重试'
        }
      }
      if (res.errno === 0) {
        success(res.data)
      } else {
        failCb(res.errmsg)
      }
    },
    fail: failCb
  })
}

export default {
  queryScore({ params, success, fail}) {
    const queryParams = {
      api: 'queryScore',
      ...params
    }
    request({
      success,
      fail,
      data: queryParams
    })
  }
}
